package com.tyq.servlet;

import org.w3c.dom.*;
import org.xml.sax.InputSource;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 调用getName
 * Created by tyq on 16/10/16.
 */
public class WSServlet extends HttpServlet {
    private static final long serialVersionUID = -3973407331774768489L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String data = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.tyq.com/\">" +
                "   <soapenv:Header/>" +
                "   <soapenv:Body>" +
                "      <ser:getName>" +
                "         <arg0>" + name + "</arg0>" +
                "      </ser:getName>" +
                "   </soapenv:Body>" +
                "</soapenv:Envelope>";
        String path = "http://127.0.0.1:8080/ws/student";
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-type", "text/xml;charset=utf-8");
        OutputStream out = connection.getOutputStream();
        out.write(data.getBytes("utf-8"));
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            InputStream is = connection.getInputStream();
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = factory.newDocumentBuilder();
                Document document = documentBuilder.parse(is);
                NodeList node_key = document.getElementsByTagName("key");
                NodeList node_value = document.getElementsByTagName("value");
                String keyValue = node_key.item(0).getChildNodes().item(0).getNodeValue();
                String nodeValue = node_value.item(0).getChildNodes().item(0).getNodeValue();
                System.out.println(keyValue+":"+nodeValue);
            }catch (Exception e){
                e.printStackTrace();
            }
            /*
            Reader reader = new InputStreamReader(is);
            字节流转字符流
            BufferedReader br = new BufferedReader(reader);
            String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + br.readLine();
            System.out.println(str);
            StringReader read = new StringReader(str);
            InputSource source = new InputSource(read);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder builder=factory.newDocumentBuilder();
                Document doc = builder.parse(source);
                Element element = doc.getDocumentElement();
            } catch (Exception e) {
                e.printStackTrace();
            }*/

            /*
            将返回的消息保存至文件中
            OutputStream os = new FileOutputStream("/Users/tyq/Downloads/test.txt");
            byte[] b = new byte[1024 * 1024];
            int len = 0;
            while ((len = is.read(b)) > 0) {
                os.write(b,0,len);
            }
            os.flush();
            os.close();
            is.close();*/

            /*
            返回消息到前端
            ServletOutputStream sos = resp.getOutputStream();
            byte[] b = new byte[1024 * 1024];
            int len = 0;
            while ((len = is.read(b)) > 0) {
                sos.write(b,0,len);
            }
            sos.flush();
            is.close();*/
        }
        out.close();
    }

}
